#!/usr/bin/env node

const { spawn } = require('child_process');
const path = require('path');

console.log('🔐 Google OAuth 测试助手');
console.log('======================');

// 检查环境配置
require('dotenv').config();

const clientId = process.env.GOOGLE_CLIENT_ID;
const clientSecret = process.env.GOOGLE_CLIENT_SECRET;
const port = process.env.PORT || 3001;

if (!clientId || !clientSecret) {
  console.log('❌ 错误：Google OAuth 环境变量未配置');
  console.log('');
  console.log('请在 .env 文件中设置：');
  console.log('GOOGLE_CLIENT_ID=your_google_client_id.apps.googleusercontent.com');
  console.log('GOOGLE_CLIENT_SECRET=your_google_client_secret');
  console.log('');
  console.log('配置指南：./docs/GOOGLE_AUTH_SETUP.md');
  process.exit(1);
}

console.log('✅ Google OAuth 环境变量已配置');
console.log('');
console.log('📋 配置信息：');
console.log(`   服务器端口: ${port}`);
console.log(`   Client ID: ${clientId.substring(0, 20)}...`);
console.log('');

console.log('🚀 启动开发服务器...');
console.log('');

// 启动开发服务器
const server = spawn('npm', ['run', 'dev'], {
  cwd: path.join(__dirname, '..'),
  stdio: 'pipe'
});

let serverStarted = false;

server.stdout.on('data', (data) => {
  const output = data.toString();
  console.log(output);
  
  // 检测服务器启动成功
  if (output.includes(`Server is running on port ${port}`) && !serverStarted) {
    serverStarted = true;
    
    setTimeout(() => {
      console.log('');
      console.log('🌐 服务器已启动！');
      console.log('');
      console.log('📋 可用的测试链接：');
      console.log(`   Google OAuth测试: http://localhost:${port}/docs/google-auth-test.html`);
      console.log(`   API文档: http://localhost:${port}/api-docs`);
      console.log(`   健康检查: http://localhost:${port}/health`);
      console.log('');
      console.log('💡 提示：');
      console.log('- 在Google Cloud Console中确保配置了正确的授权JavaScript来源');
      console.log(`- 授权来源应包含：http://localhost:${port}`);
      console.log('- 使用 Ctrl+C 停止服务器');
      console.log('');
      
      // 尝试自动打开浏览器（可选）
      const open = require('child_process').spawn;
      try {
        if (process.platform === 'darwin') {
          open('open', [`http://localhost:${port}/docs/google-auth-test.html`]);
        } else if (process.platform === 'win32') {
          open('start', [`http://localhost:${port}/docs/google-auth-test.html`], { shell: true });
        } else {
          open('xdg-open', [`http://localhost:${port}/docs/google-auth-test.html`]);
        }
        console.log('🌍 已尝试在浏览器中打开测试页面');
      } catch (error) {
        console.log('💭 请手动在浏览器中打开测试页面');
      }
    }, 2000);
  }
});

server.stderr.on('data', (data) => {
  console.error(data.toString());
});

server.on('close', (code) => {
  console.log(`\n🏁 服务器已停止 (退出码: ${code})`);
});

// 处理进程退出
process.on('SIGINT', () => {
  console.log('\n👋 正在停止服务器...');
  server.kill('SIGINT');
}); 